package com.htc.dlc.fragment;

import java.util.ArrayList;
import java.util.List;

import com.htc.adapter.SpaAdapter;
import com.htc.adapter.WellnessOverviewAdapter;
import com.htc.adapter.SpinnerAdapter1;
import com.htc.common.ActionEvent;
import com.htc.constants.Constants;
import com.htc.controller.WellnessOverviewController;
import com.htc.dlc.R;
import com.htc.dlc.SpaActivity;
import com.htc.model.dto.FitnessGroupDTO;
import com.htc.model.dto.SpaParentDTO;
import com.htc.model.dto.WellnessOverviewDTO;
import com.htc.model.utils.FitnessModel;
import com.htc.model.utils.SpasModel;
import com.htc.model.utils.WellnewssOverviewModel;
import com.htc.slidingmenu.library.CirclePageIndicator;
import com.htc.slidingmenu.library.PageIndicator;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;

public class FragmentWellnessOverview extends Fragment {
	ListView lv_wellnessoverview;
	Spinner spinner;
	View header;
	View footer;
	Handler handler;
	public static final int DELAY = 5000;
	ViewPager mPager;
	PageIndicator mIndicator;
	ArrayList<FitnessGroupDTO> arrGroupList;
	SpinnerAdapter1 adapter;
	ArrayList<Object> arrData;
	WellnessOverviewAdapter adapterwell;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		ImagePagerAdapter adapterimg = new ImagePagerAdapter();
		mPager.setAdapter(adapterimg);

		mIndicator.setViewPager(mPager);

		FitnessModel md = FitnessModel.getInstance();
		arrGroupList = md.getAllFitnessGroup(getActivity());
		if ((arrGroupList != null) && (arrGroupList.size() > 0)) {
			FitnessGroupDTO localFitnessGroupModel = new FitnessGroupDTO();
			localFitnessGroupModel.setFitnessGroupName("All");
			arrGroupList.add(0, localFitnessGroupModel);
			adapter = new SpinnerAdapter1(getActivity(), 0, arrGroupList);
			spinner.setAdapter(adapter);
		}

		arrData = new ArrayList<Object>();
		adapterwell = new WellnessOverviewAdapter(getActivity(),
				R.layout.fragment_wellness_overvview_row, arrData);
		lv_wellnessoverview.setAdapter(adapterwell);
		initData();

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {

				if (((FitnessGroupDTO) arrGroupList.get(position))
						.getFitnessGroupName().equalsIgnoreCase("All")) {
					WellnewssOverviewModel md = WellnewssOverviewModel
							.getInstance();

					ArrayList<Object> arrList = new ArrayList<Object>();
					arrList = md
							.getAllwellnessOverview1(FragmentWellnessOverview.this);

					adapterwell = new WellnessOverviewAdapter(getActivity(),
							R.layout.fragment_wellness_overvview_row, arrList);
					lv_wellnessoverview.setAdapter(adapterwell);
					adapterwell.notifyDataSetChanged();
					// tv_title_spa.setText("All");
				} else {
					adapter.selectedString = ((FitnessGroupDTO) arrGroupList
							.get(position)).getFitnessGroupName();
					WellnewssOverviewModel md = WellnewssOverviewModel
							.getInstance();
					ArrayList<Object> spaChildList = md.getAllOverview(
							((FitnessGroupDTO) arrGroupList.get(position))
									.getFitnessGroupId(), getActivity());
					adapterwell = new WellnessOverviewAdapter(getActivity(),
							R.layout.fragment_wellness_overvview_row, spaChildList);
					lv_wellnessoverview.setAdapter(adapterwell);
					adapterwell.notifyDataSetChanged();
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_wellness_overview,
				container, false);
		lv_wellnessoverview = (ListView) rootView
				.findViewById(R.id.lv_wellnessoverview);
		header = getActivity().getLayoutInflater().inflate(
				R.layout.wellness_overview_header, null);

		footer = getActivity().getLayoutInflater().inflate(
				R.layout.activity_footer, null);
		lv_wellnessoverview.addHeaderView(header);
		lv_wellnessoverview.addFooterView(footer);
		this.mPager = (ViewPager) header.findViewById(R.id.pager);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		mPager.getLayoutParams().height = height*1/3;
		mIndicator = (CirclePageIndicator) header.findViewById(R.id.indicator);
		spinner = (Spinner) header.findViewById(R.id.spin_wellnesssearch);
		return rootView;
	}

	private void initData() {
		ActionEvent e = new ActionEvent(this, Constants.GET_WELL_OVERVIEW,
				null, null);
		WellnessOverviewController.getInstance().handleViewEvent(e);
	}

	@SuppressWarnings("unchecked")
	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_WELL_OVERVIEW:
			ArrayList<WellnessOverviewDTO> newArr = (ArrayList<WellnessOverviewDTO>) e.viewData;

			new VerySlowTask(newArr).execute();
			break;
		default:
			break;
		}
	}

	public class VerySlowTask extends AsyncTask<String, Object, Void> {
		List<WellnessOverviewDTO> _newArr;

		public VerySlowTask(List<WellnessOverviewDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				for (int i = 0; i < _newArr.size(); i++) {
					publishProgress(_newArr.get(i));

				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapterwell.notifyDataSetChanged();
		}

	}

	private class ImagePagerAdapter extends PagerAdapter {
		private int[] mImages = new int[] { R.drawable.wellness1,
				R.drawable.wellness2, R.drawable.wellness3 };

		@Override
		public int getCount() {
			return mImages.length;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Context context = getActivity();
			ImageView imageView = new ImageView(context);
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			imageView.setImageResource(mImages[position]);

			((ViewPager) container).addView(imageView, 0);
			return imageView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((ImageView) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return (view == object);
		}

		/**
		 * Called when the a change in the shown pages has been completed. At
		 * this point you must ensure that all of the pages have actually been
		 * added or removed from the container as appropriate.
		 * 
		 * @param arg0
		 *            The containing View which is displaying this adapter's
		 *            page views.
		 */
		@Override
		public void finishUpdate(ViewGroup arg0) {
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(ViewGroup arg0) {
		}
	}

}
